package com.harvest.scientific.ladder.net

import androidx.lifecycle.Observer
import com.google.gson.JsonParseException
import org.json.JSONException
import retrofit2.HttpException
import java.io.InterruptedIOException
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import java.text.ParseException

/**
 * @Author: 633578
 * @Desc:  http 请求过程中异常处理
 */
object ExUtils {

    const val EXCEPTION_JSON_CODE = -10001
    const val EXCEPTION_CONNECT_CODE = -10002
    const val EXCEPTION_SOCKET_CODE = -10003
    const val EXCEPTION_INTERRUPTEDIO_CODE = -10004
    const val EXCEPTION_UN_KNOW_HOST_CODE = -10005
    const val EXCEPTION_UN_KNOW_CODE = -10006

    private var observer: Observer<Int?>? = null

    fun setHttpCodeListener(observer: Observer<Int?>?) {
        this.observer = observer
    }

    fun handleException(code: Int?, msg: String?) {
        this.observer?.onChanged(code)
    }

    fun handleException(e: Throwable?): Pair<Int, String> {
        val pair: Pair<Int, String> = when (e) {
            is HttpException -> {
                Pair(e.code(), "${e.message}")
            }
            is JsonParseException, is JSONException, is ParseException -> {
                Pair(EXCEPTION_JSON_CODE, "${e.message}")
            }
            is ConnectException -> {
                Pair(EXCEPTION_CONNECT_CODE, "${e.message}")
            }
            is SocketTimeoutException -> {
                Pair(EXCEPTION_SOCKET_CODE, "${e.message}")
            }
            is InterruptedIOException -> {
                Pair(EXCEPTION_INTERRUPTEDIO_CODE, "${e.message}")
            }
            is UnknownHostException -> {
                Pair(EXCEPTION_UN_KNOW_HOST_CODE, "${e.message}")
            }
            else -> {
                Pair(EXCEPTION_UN_KNOW_CODE, "${e?.message}")
            }
        }
        return pair;
    }

    const val EX_JOB_WAS_CANCELED = "job was cancelled"

    const val EX_SOFTWARE_CONNECT_ABORT = "software caused connection abort"
}